const express = require('express');
const router = express.Router();
const Admin = require('../../models/Admin');
const Session = require('../../models/Session');
const Message = require('../../models/Message');
const Competition = require('../../models/Competition');
const authenticateToken = require('../../middlewares/authenticateToken');
const mongoose=require('mongoose')

//获取所有征文列表
router.get('/article/getCompetitionList', authenticateToken, async (req, res) => {
  try {
    // 1. 接收前端参数：分页参数（默认第1页，每页10条）+ 状态筛选（可选）
    const { 
      page = 1, 
      limit = 10, 
      status = '' // 可选筛选：未开始/进行中/已结束
    } = req.query;

    // 2. 构造查询条件：状态有值则筛选，无值则查全部
    const queryCondition = status ? { status } : {};

    // 3. 数据库查询：关联创建人昵称 + 分页 + 排序
    const skip = (page - 1) * Number(limit); // 计算跳过条数
    const competitionList = await Competition.find(queryCondition)
      .populate({
        path: 'creatorId', // 关联Admin模型获取创建人信息
        model: 'Admin',
        select: 'nickname' // 仅返回昵称，避免敏感信息
      })
      .sort({ startDate: -1 }) // 按开始时间倒序（最新征文在前）
      .skip(skip)
      .limit(Number(limit))
      .select('-__v'); // 排除MongoDB默认的__v字段

    // 4. 查询总条数（用于分页计算）
    const total = await Competition.countDocuments(queryCondition);

    // 5. 格式化响应数据（统一字段格式，空值兜底）
    const formattedList = competitionList.map(competition => ({
      id: competition._id.toString(), // 征文ID（字符串格式，便于前端存储）
      title: competition.title,
      theme: competition.theme || '无主题',
      description: competition.description || '无描述',
      startDate: competition.startDate, // 字符串格式日期（与模型一致）
      endDate: competition.endDate,
      status: competition.status, // 未开始/进行中/已结束
      creatorId: competition.creatorId?._id.toString() || '',
      creatorName: competition.creatorId?.nickname || '未知创建人',
      cover: competition.cover || '', // 封面URL（空则无封面）
      platform: competition.platform || '无',
      awards: competition.awards || '无',
      rules: competition.rules || '无'
    }));

    // 6. 统一响应格式
    res.json({
      code: '0000',
      msg: '获取征文列表成功',
      data: {
        list: formattedList,
        pagination: {
          total: total, // 总条数
          page: Number(page), // 当前页码
          limit: Number(limit), // 每页条数
          totalPages: Math.ceil(total / Number(limit)) // 总页数（便于前端分页控件）
        }
      }
    });
  } catch (err) {
    console.error('获取征文列表失败：', err);
    res.json({
      code: '500',
      msg: '服务异常：' + err.message,
      data: {
        list: [],
        pagination: { total: 0, page: 1, limit: 10, totalPages: 0 }
      }
    });
  }
});


//获取单个征文详情
router.get('/article/getCompetitionInfo', authenticateToken, async (req, res) => {
  try {
    // 1. 提取请求参数：征文ID（必传）
    const { id: competitionId } = req.query;

    // 2. 校验：必须传递征文ID
    if (!competitionId) {
      return res.json({
        code: '400',
        msg: '请传入征文ID（id字段）',
        data: {}
      });
    }

    // 3. 校验ID格式有效性
    if (!mongoose.Types.ObjectId.isValid(competitionId)) {
      return res.json({
        code: '400',
        msg: '征文ID格式错误',
        data: {}
      });
    }

    // 4. 查询征文详情（关联创建人昵称）
    const competitionDetail = await Competition.findById(competitionId)
      .populate({
        path: 'creatorId',
        model: 'Admin',
        select: 'nickname' // 仅返回创建人昵称
      })
      .select('-__v'); // 排除MongoDB默认的__v字段

    // 5. 处理查询结果：征文不存在则返回404
    if (!competitionDetail) {
      return res.json({
        code: '404',
        msg: '征文不存在或已被删除',
        data: {}
      });
    }

    // 6. 格式化响应数据（空值兜底）
    const formattedDetail = {
      id: competitionDetail._id.toString(),
      title: competitionDetail.title,
      theme: competitionDetail.theme || '无主题',
      description: competitionDetail.description || '无描述',
      startDate: competitionDetail.startDate,
      endDate: competitionDetail.endDate,
      status: competitionDetail.status,
      creatorId: competitionDetail.creatorId?._id.toString() || '',
      creatorName: competitionDetail.creatorId?.nickname || '未知创建人',
      cover: competitionDetail.cover || '',
      platform: competitionDetail.platform || '无',
      awards: competitionDetail.awards || '无',
      rules: competitionDetail.rules || '无',
    };

    // 7. 统一响应格式
    res.json({
      code: '0000',
      msg: '获取征文详情成功',
      data: formattedDetail
    });
  } catch (err) {
    console.error('获取征文详情失败：', err);
    res.json({
      code: '500',
      msg: '服务异常：' + err.message,
      data: {}
    });
  }
});


module.exports = router;